//init app
var AccountOverview = Em.Application.create({
	isAccountDetailsLoaded:false,
	currentAccount:'',
	currentTransaktion: '',
	
	//calculated property. Is always an inverse of "isAccountDetailsLoaded".
	isAccountTransactionsLoaded : function() {
		var details = this.get('isAccountDetailsLoaded');
		return !details;
	}.property('isAccountDetailsLoaded'),
	
	//runs automagically when application is created 
	ready : function() {
		AccountOverview.overviewController.initAccounts();
	}
});

//View
AccountOverview.MobileBaseView = Em.View.extend({
    attributeBindings:['data-role']
});

AccountOverview.PageView = AccountOverview.MobileBaseView.extend({
    'data-role': 'page'
});

AccountOverview.ToolbarBaseView = AccountOverview.MobileBaseView.extend({
    attributeBindings:['data-position'],
    'data-position': function() {
        if (this.get('isFullScreen')) {
            return 'fullscreen';
        }

        if (this.get('isFixed')) {
            return 'fixed';
        }
        return '';
    }.property('isFixed', 'isFullScreen').cacheable(),

    isFixed: true,
    isFullsScreen: false
});

AccountOverview.HeaderView = AccountOverview.ToolbarBaseView.extend({
    'data-role': 'header'
});

AccountOverview.ContentView = AccountOverview.MobileBaseView.extend({
	className:'ui-grid-b'
});

AccountOverview.OverViewView = AccountOverview.PageView.extend({
	templateName:'overview',
	id: 'main-view',
	attributeBindings: ['data-url'],
	'data-url':'overview',
	//Can this function be removed?
	didInsertElement: function() {
		$.mobile.changePage(this.$());
	}
});

AccountOverview.ListItemView = Em.View.extend({
	attributeBindings: ['data-theme'],
	'data-theme':'c',
    tagName: 'li'
});

AccountOverview.ListView = Em.CollectionView.extend({
    attributeBindings: ['data-role'],
    'data-role':'listview',
    tagName: 'ul',
    itemViewClass: AccountOverview.ListItemView,
});

AccountOverview.AccountView = Em.View.extend({
	tagName: 'li',
	content: null,
	linkClicked: function(){
		arId = this.getPath('content.arrangementId');
		AccountOverview.set('currentAccount',arId);
		AccountOverview.set('isAccountDetailsLoaded',false);
		
        AccountOverview.transactionController.retrieveTransactionsWithArId(arId, false);
	},
	contentLengthDidChange: function(){
        Em.run.next(function() {
            $('#accountlist').listview('refresh');
        });
    }.observes('content.length')
});

AccountOverview.TransactionView = Em.View.extend({
	tagName: 'li',
	content: null,
	
	linkClicked: function(){
		id = this.getPath('content.id');
		AccountOverview.set('currentTransaktion', id);
		AccountOverview.transactionDetailsController.retrieveDetailWithId(id);
	}
});

// Model
AccountOverview.Account = Em.Object.extend();
AccountOverview.Transaction = Em.Object.extend();
AccountOverview.AccountDetail = Em.Object.extend();
AccountOverview.TransactionDetail = Em.Object.extend();

// Controller
AccountOverview.transactionController = Em.ArrayController.create({
	content : [],
	numberOfTransactions: 0,
	moreTransactionsExist: true,
	isLoaded: false,
	retrieveTransactionsWithArId : function(arId, fetchAdditionalTransactions) {
		AccountOverview.transactionController.set('isLoaded',false);
		var self = this;
		if(!fetchAdditionalTransactions){
			//Trying to fetch for the first time (for this account)
			self.clear();
			//Can these two rows be removed?
			AccountOverview.transactionController.set('numberOfTransactions',0);
			AccountOverview.transactionController.set('moreTransactionsExist',true);
		}
		//Retrieving transactions for arId
		$('body').addClass('ui-loading');
		$.getJSON("../rest/transactions/" + arId + "/" + self.numberOfTransactions + "/", function(data) {
			if(data && data.transactions){
				  self.set('numberOfTransactions', self.numberOfTransactions + data.transactions.length);
				  if(self.numberOfTransactions==data.numberOfAvailableTransactions){
					  self.set('moreTransactionsExist',false);
				  }
				  for ( var i = 0; i < data.transactions.length; i++) {
					  self.pushObject(AccountOverview.Transaction.create(data.transactions[i]));
				  }  
			  }
			  AccountOverview.transactionController.set('isLoaded',true);
			$('body').removeClass('ui-loading');
		});
	},
	
	viewTransactions : function() {
		AccountOverview.transactionController.retrieveTransactionsWithArId(AccountOverview.currentAccount, false);
		AccountOverview.set('isAccountDetailsLoaded',false);
	},
	
	viewDetails : function() {
		if(!(AccountOverview.accountDetailsController.accountDetailsLoadedForAccount == AccountOverview.currentAccount)){
			AccountOverview.accountDetailsController.retrieveAccountWithArId(AccountOverview.currentAccount);
		}
		AccountOverview.set('isAccountDetailsLoaded',true);
	},
	loadMoreTransactions : function(){
		var arId = AccountOverview.get('currentAccount');
		AccountOverview.transactionController.retrieveTransactionsWithArId(arId, true);
	}

});

AccountOverview.accountDetailsController = Em.ArrayController.create({
	content: [],
	accountDetailsLoadedForAccount: null,
	retrieveAccountWithArId : function(arId) {
		var self = this;
		self.clear();
		$('body').addClass('ui-loading');
		$.getJSON("../rest/accounts/" + arId + "/", function(data) {
			self.pushObject(AccountOverview.AccountDetail.create(data));
			self.set('accountDetailsLoadedForAccount',arId);
			$('body').removeClass('ui-loading');
		});
	}
});

AccountOverview.transactionDetailsController = Em.ArrayController.create({
	content: [],
	retrieveDetailWithId : function(id) {
		var self = this;
		self.clear();
		$('body').addClass('ui-loading');
		
		//Try to change this and use $.getJSON() instead.
		$.ajax({  
			  url: "../rest/transactiondetail/" + id + "/",
			  dataType: 'json',  
			  data: null,  
			  async: false,  
			  success: function(data){ 
				  self.pushObject(AccountOverview.TransactionDetail.create(data));
			  }  
		});
		$('body').removeClass('ui-loading');
	}
});

AccountOverview.overviewController = Em.ArrayController.create({
	content : [],
	initAccounts: function() {
		var self = this;
		$('body').addClass('ui-loading');
//		$.ajax({  
//			  url: "../rest/accounts/",  
//			  dataType: 'json',  
//			  data: null,  
//			  async: true,  
//			  success: function(data){  
//				  for ( var i = 0; i < data.account.length; i++) {
//						self.pushObject(AccountOverview.Account.create(data.account[i]));
//				  }
//				  $('body').removeClass('ui-loading');
//			  }  
//		});
		$.getJSON("../rest/accounts/", function(data) {
			for ( var i = 0; i < data.account.length; i++) {
				self.pushObject(AccountOverview.Account.create(data.account[i]));
			}
			$('body').removeClass('ui-loading');
		});
		
	}
});


//Runs when in mobile web browsers
$(document).bind('mobileinit', function() {
    $.mobile.touchOverflowEnabled = true;
//    var v = AccountOverview.get('overview');
//    if (!v) {
//        v = AccountOverview.OverViewView.create();
//        AccountOverview.set('overview',v);
//        v.append();
//    }
});

//Runs when in desktop web browsers 
$(document).bind('pageinit', function(){
    var v = AccountOverview.get('overview');
    if (!v) {
        v = AccountOverview.OverViewView.create();
        AccountOverview.set('overview',v);
        v.append();
    }
});
